﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iLangl.Utils;
using System.Data;

namespace iLangl.LanguageWire.DAL.LanguageWireDAL.MockupStorage
{
	public class MockupStorageManager : BaseMockupStorageManager
	{
		private MockupStorageManager(string filename)
			: base(filename)
		{
		}

		private static MockupStorageManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the MockupStorageManager.
		/// </summary>
		public static MockupStorageManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new MockupStorageManager(MockupStorageConfiguration.Instance.FilePathToStorage);
						}
					}
				}
				return instance;
			}
		}

		private dtoMockupStorage _storage = null;
		public dtoMockupStorage Storage
		{
			get
			{
				if (_storage == null)
				{
					_storage = new dtoMockupStorage();

					if (!File.Exists(StorageFileName))
					{
						Save();
					}

					read();
				}

				return _storage;
			}
		}

		public void AcceptChanges()
		{
			Storage.AcceptChanges();
			Save();
		}

		protected override void readStorage()
		{
			_storage = new dtoMockupStorage();

			foreach (DataTable dataTable in _storage.Tables)
				dataTable.BeginLoadData();

			_storage.ReadXml(StorageFileName);

			foreach (DataTable dataTable in _storage.Tables)
				dataTable.EndLoadData();
		}

		protected override void saveStorage()
		{
			Storage.WriteXml(StorageFileName);
		}
	}
}